#!perl  -I /data/scripts/lib

use strict;
use warnings;
use Data::Dumper 'Dumper';
use Functions;
use Connect;

sub db_insert
{
    my $hRefParam=shift @_;
    my $ref_data=shift @_;
    my $insert_date = "";
    $insert_date=Functions::get_date("-")." ".Functions::get_time(":");
    my $event_id=0;
    my $res=0;

    $hRefParam->{DBCONNECT}=Connect::db_con($hRefParam->{DBNAME},$hRefParam->{DBLOGIN},$hRefParam->{DBPASSWD});
    if (! defined $hRefParam->{DBCONNECT})
    {
	#Functions::error "Failed to connect to DB.\n";
	# Failed to connect to DB
	return 0;
    }

    # create an event
    $hRefParam->{DBCONNECT}->do("LOCK TABLES event WRITE") || die "LOCK TABLES failed";
    my $sth = $hRefParam->{DBCONNECT}->prepare("INSERT INTO event (event_type_id,date,data) VALUES (2,'$insert_date',0);");
    $res=$sth->execute();
    $event_id=$hRefParam->{DBCONNECT}->{ q{mysql_insertid}};
    $hRefParam->{DBCONNECT}->do("UNLOCK TABLES") || die "UNLOCK TABLES failed";
    
    foreach my $elements (@$ref_data)
    {
	my ($imei,$data)=split(";",$elements);
	chomp($data);
	#print "imei -> ".$imei." data -> ".$data."\n";

	# check whether imei exists in DB with data
	$sth = $hRefParam->{DBCONNECT}->prepare("select count(*) from imei where imei='$imei' and data!='0'");
	$sth->execute();
	my $ref = $sth->fetchrow_hashref();
	$sth->finish();

	if ($ref->{'count(*)'} == 0)
	{
	    print "imei or data not found for imei ".$imei.".Inserting...\n";
	    $sth = $hRefParam->{DBCONNECT}->prepare("insert into imei (imei,event_id,data,imei_additional_info_id) values ('$imei','$event_id','$data',0);");
	    $sth->execute();
	}
    }

    Connect::db_discon($hRefParam->{DBCONNECT});

    return 1;
}

sub get_enciphered_data
{
    my $href_data=shift @_;
    my $imei="";
    my $cmd="";
    my @output=();
    my @enciphered_data=();
    
    foreach $imei (keys %{$href_data} )
    {
	$cmd="/data/scripts/get_enciphered_data.pl $imei '$href_data->{$imei}'";
	@output=`$cmd`;
	push(@enciphered_data,$output[0]);
    }

    return @enciphered_data;
}

sub fill
{
    my $href_data=shift @_;
    my $data=shift @_;
    my $imei="";
    my $keys="";
    my $requestid="";
    my $requester="";

    my @fields=split(";",$data);

    $requestid=shift @fields;
    $requester=shift @fields;
    $imei=shift @fields;
    $keys = join (';',@fields);

    $href_data->{"$imei"}=$keys;
}

sub myprint
{
    my $href_data=shift @_;
    my $imei="";

    foreach $imei (keys %{$href_data} )
    {
	print "imei -> ".$imei." data -> ".$href_data->{$imei};
    }
}

sub process
{
    my $hRefParam=shift @_;
    my %data=();
    my $bfile="";
    my $in;
    my $line="";
    my @enciphered_data=();
    my $hash_size=0;
    my $err=0;

    #Functions::print_hash_content($hrefParam);

    $bfile=`basename $hRefParam->{INPUT_FILE}`;
    chomp($bfile);

    Functions::info "Processing file $bfile....\n";

    open($in, "< $hRefParam->{INPUT_FILE}") || die Functions::error "Failed to open $bfile.\n";;
    while ( $line= <$in>)
    {
	if($line=~m/^.+\d{15};\d{10}/)
	{
	    fill(\%data,$line);
	}
    }

    #Functions::print_hash_content(\%data);

    $hash_size=Functions::get_hash_size(\%data);
    if($hash_size == 0)
    {
	Functions::info "No data to update.\n";
	  goto ENDPROCESS;
    }
    #print "size of data -> ".$hash_size."\n";
    #myprint(\%data);
    Functions::info "Enciphering data.\n";
    @enciphered_data=get_enciphered_data(\%data);

    #warn Dumper[@enciphered_data];

    Functions::info "Updating DB...\n";
    if(! db_insert($hRefParam,\@enciphered_data))
    {
	Functions::error "Failed to connect to DB.\n";
	  return 1;
    }

  ENDPROCESS:;
    Functions::info "End of process.\n";

    return $err;

}

sub parse_args
{
    my $hRefParam=shift @_;

    my $arg="";
    my $err=0;
    
    while ($arg=shift @ARGV)
    {
	chomp($arg);
	if (! exists $hRefParam->{DBNAME})
	{
	    $hRefParam->{DBNAME}=$arg;
	}
	elsif (! exists $hRefParam->{DBLOGIN})
	{
	    $hRefParam->{DBLOGIN}=$arg;
	}
	elsif (! exists $hRefParam->{DBPASSWD})
	{
	    $hRefParam->{DBPASSWD}=$arg;
	}
	elsif (! exists $hRefParam->{INPUT_FILE})
	{
	    $hRefParam->{INPUT_FILE}=$arg;
	}
	else
	{
	    Functions::error "Unexpected option >$arg<.\n";
	    $err++;
	    next;
	} 
	
    }	
	
    if (! exists $hRefParam->{INPUT_FILE})
    {
	Functions::error "Missing mandatory arguments..\n";
	  print "Usage: ".$hRefParam->{EXECUTABLE_NAME}." <dbname> <dblogin> <dbpasswd> <input file>\n";
	  $err++;
    }
    
    
    if ($err>0)
    {
	return 1;
    }
    
    return 0;
}

sub intro
{
    my $hRefParam=shift @_;
    my $err=0;

    $hRefParam->{EXECUTABLE_NAME}="imei.pl";

    # Following instruction forces flushing for each output to STDOUT
    $|=1;
    
    return $err;
}

sub outro
{
    my $hRefParam=shift @_;
    my $err=0;

    return $err;
}

sub main
{
    my %params=();
    my $errcode;
    
    if (intro(\%params)!=0)
    {
	Functions::error "Error while executing intro. Aborting...\n";
	exit(1);
    }
    
    if (parse_args(\%params)!=0)
    {
	Functions::error "Error while parsing arguments. Aborting...\n";
	  exit(1);
    }

    if(process(\%params)!=0)
    {
	Functions::error "Error while processing. Aborting...\n";
	  exit(1);
    }
}

main();

exit ;
